package main

import (
	"bufio"
	"io/fs"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	path := inputStr("请输入目录", reader)
	ffmpeg := inputStr("请输入ffmpeg目录", reader)
	if IsEmpty(ffmpeg) {
		ffmpeg = "ffmpeg"
	}
	startFile := inputStr("请输入开始文件名称", reader)

	flag := false
	if IsEmpty(startFile) {
		flag = true
	}

	rd, err := ioutil.ReadDir(path)
	if nil != err {

		log.Println(path, "读取错误", err)
		return
	}

	if existsDir("Clarity") {
		os.MkdirAll("Clarity", os.ModePerm)
	}

	for _, fi := range rd {
		if !fi.IsDir() {
			if flag {
				chooseFile(fi, path, ffmpeg)
			} else if fi.Name() == startFile {
				flag = true
				chooseFile(fi, path, ffmpeg)
			}

		}
	}
	log.Println("------------------over----------------------")
}

func cmdExit(cmd *exec.Cmd) {
	defer func() { cmd = nil }()
	exec.Command("exit")
	cmd.Run()
}
func IsEmpty(str string) bool {

	return len(str) == 0
}

/*判断文件夹是否存在*/
func existsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return os.IsNotExist(err)
	}
	return !s.IsDir()
}

func inputStr(tip string, reader *bufio.Reader) string {
	log.Println(tip)
	value, _ := reader.ReadString('\n')
	return strings.TrimSpace(value)
}

func chooseFile(fi fs.FileInfo, path string, ffmpeg string) {
	index := strings.LastIndex(fi.Name(), ".")
	length := len(fi.Name())

	path1 := path + "/" + fi.Name()
	path2 := "Clarity/" + fi.Name()[0:index] + ".2." + fi.Name()[index+1:length]

	log.Println(fi.Name(), "---start---", path1, path2)
	cmd := exec.Command(ffmpeg, "-i", path1, "-b", "16000k", "-vcodec", "libx264", "-y", path2)
	cmdExit(cmd)
	cmd.Run()
	log.Println(fi.Name(), "---over---", path1, path2)
}
